<template>
  <div v-loading="loading">
    <b-table
      ref="table"
      :disabled="disabled"
      :columns="columns"
      :scroll="{ x: 1300 }"
      :request="loadData"
      :delFunc="delFunc"
      :export-config="{ use: true, select: '混凝土需用明细', all: '混凝土需用明细' }"
    >
      <template v-if="!disabled" slot="prefix" slot-scope="ref">
        <a-button type="primary" @click="openDialog"> 添加行</a-button>
        <!--        <a-button @click="ref.delete(delFunc)"> 删除行</a-button>-->
      </template>
      <template slot="index" slot-scope="text, record, index">{{ index + 1 }}</template>
      <template
        v-for="(col, i) in ['planVolume','slump','castingParts','castingTime',
        'dischargeWay','volumeFormula' ]"
        :slot="col"
        slot-scope="text, record, index"
      >
        <template v-if="!disabled">
          <a-date-picker
            v-if="col === 'castingTime'"
            v-model="record[col]"
            class="requiredFormItem"
            value-format="YYYY-MM-DD"
            @change="(e) => handleChange(e, record)"
          />
          <BaseInputNumber
            v-else-if="col === 'planVolume'"
            v-model="record[col]"
            class="requiredFormItem"
            :precision="2"
            :min="0"
            @blur="(e) => handleChange(e, record)"
          />
          <BaseInput
            class="requiredFormItem"
            v-else
            v-model="record[col]"
            @blur="(e) => handleChange(e.target.value, record)"
          />
        </template>
        <template v-else>
          {{ text }}
        </template>
      </template>
    </b-table>
    <materialListAndDir
      ref="detailDialog"
      :mode="'single'"
      :api="findMonthDetailsByMonthId"
      :request-params="{needCount:true, materialMonthId:materialMonthId }"
      @createList="createList"
    />
  </div>
</template>
<script>
import {
  exportByDetailsLease
} from '@/api/material/settlement/settlement'
import ExportMould from '@/components/ExportMould'
import materialListAndDir from '@/components/materialListAndDir/materialListAndDir'
import Api from '@/api/material/plan/concreteApply.js'

export default {
  components: {
    ExportMould,
    materialListAndDir
  },
  props: {
    disabled: {
      type: Boolean
    },
    id: {
      type: String
    },
    materialMonthId: {
      type: String
    }
  },
  data() {
    return {
      loading: false,
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'index' },
          width: '70px'
        },
        {
          title: '物资名称',
          width: '150px',
          dataIndex: 'name'
        },
        {
          title: '规格型号',
          width: '150px',
          dataIndex: 'specificationModel'
        },
        {
          title: '计划方量',
          width: '150px',
          dataIndex: 'planVolume',
          scopedSlots: { customRender: 'planVolume' }
        },
        {
          title: '塌落度',
          width: '150px',
          dataIndex: 'slump',
          scopedSlots: { customRender: 'slump' }
        },
        {
          title: '浇筑部位',
          width: '150px',
          dataIndex: 'castingParts',
          scopedSlots: { customRender: 'castingParts' }
        },
        {
          title: '浇筑时间',
          dataIndex: 'castingTime',
          width: '150px',
          scopedSlots: { customRender: 'castingTime' }
        },
        {
          title: '卸料方式',
          dataIndex: 'dischargeWay',
          width: '150px',
          scopedSlots: { customRender: 'dischargeWay' }
        },
        {
          title: '方量计算式',
          dataIndex: 'volumeFormula',
          width: '150px',
          scopedSlots: { customRender: 'volumeFormula' }
        }
      ],
      findMonthDetailsByMonthId: Api.findMonthDetailsByMonthId,
      rateArr: [],
      delFunc: Api.deleteByByDetailList,
      loadData: (params) => Api.findListByDetails({ ...params, 'query': { 'baseId': this.id } })
    }
  },
  methods: {
    async importFunc(e) {
      let newTable = [],
        newTableTit = [],
        colEmpty = [],
        emptyTip = '',
        noneColArr = []
      e.map((row, num) => {
        let temp = {}
        newTableTit[num] = []
        for (const rowKey in row) {
          newTableTit[num].push(rowKey)
          let column = this.columns.find((columnRow) => columnRow.title === rowKey)
          if (column) {
            let dataIndex = column.dataIndex
            if (dataIndex === 'isFloatHalfDayStr') {
              temp.floatHalfDay = row[rowKey] === '是' ? true : false
            } else {
              temp[dataIndex] = row[rowKey]
            }
          }
        }
        temp.settleId = this.id
        newTable.push(temp)
        //验证未填项
        let col = [
          '物料名称',
          '物料编码',
          '规格型号',
          '计量单位',
          '租赁数量',
          '本期计算起始时间',
          '本期计算结束时间',
          '是否浮动半天',
          '不含税单价（元）',
          '税率'
        ]
        noneColArr[num] = []
        col.forEach((item, index) => {
          let status = newTableTit[num].includes(item)
          if (!status) {
            noneColArr[num].push(item)
          }
        })
        if (noneColArr[num].length > 0) {
          colEmpty[num] = {
            name: noneColArr[num],
            num: num + 1
          }
        }
      })
      if (colEmpty.length > 0) {
        for (let item in colEmpty) {
          emptyTip += '第' + colEmpty[item].num + '行：' + colEmpty[item].name + '\r\n'
        }
        emptyTip = '请完整输入内容：\r\n' + emptyTip
        this.$notification.open({ message: '提示', duration: null, description: () => <pre>{emptyTip}</pre> })
        return false
      }
      try {
        this.loading = true
        let res = await exportByDetailsLease(newTable)
        let msg = res.message
        this.loading = false
        this.$refs.table.getData(null, true)
        this.$notification.open({ message: '提示', duration: null, description: () => <pre>{msg}</pre> })
      } catch (e) {
        this.loading = false
      }
    },
    openDialog: function() {
      this.$refs.detailDialog.open()
    },
    async createList(selectRow) {
      let temp = []
      selectRow.map((item) => {
        temp.push({
          baseId: this.id,
          materialId: item.id,
        })
      })
      this.loading = true
      let res = await Api.createByDetails(temp)
      this.loading = false
      if (res.code === 200) {
        this.$refs.table.getData(null, true)
      }
    },
    async handleChange(value, target) {
      await Api.editByByDetail(target)
    }
  }
}
</script>